<?php
namespace common\logic;

use common\models\OrderStatusFlow;
use common\tool\Currency;
use Yii;
use common\models\Order as OrderModel;
use Overtrue\Pinyin\Pinyin;

/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/03/18
 * 统一用生成的orderId, order表主键id不用
 */
class Order {
    const PAY_TYPE_ALI = 1;
    const PAY_TYPE_WECHAT = 2;
    const PAY_TYPE_ALI_WAP = 3;
    const PAY_TYPE_WECHAT_H5 = 4;
    public static function generateOrderid() {
        return date('YmdHis') . mt_rand(1000000000, 9999999999);
    }

    public static function getDetail($uid, $orderId) {
        $r = OrderModel::getOne("order_id=:orderId", '*', [':orderId' => $orderId]);
        $r['payment'] = json_decode($r['payment'], true);
        if ($r['uid'] != $uid) {
            return [
                'err' => 1,
                'msg' => '无权限',
            ];
        }
        if(!$r){
            return['err'=>2,'msg'=>'订单不存在'];
        }
        return [
            'err' => 0,
            'data' => $r,
        ];
    }

    public static function getOrderAdmin($orderId) {
        $r = OrderModel::getOne("order_id='$orderId'");
        $r['payment'] = $r['payment'] ? json_decode($r['payment'], true) : [];
        $r['ext'] = $r['ext'] ? json_decode($r['ext'], true) : [];
        $r['contact'] = $r['contact'] ? json_decode($r['contact'], true) : [];
        return $r;
    }

    public static function getOrders($uid, $page = 1, $limit = 20) {
        $offset = ($page - 1) * $limit;
        $r = OrderModel::getList("uid=$uid", '*', 'utime DESC', $offset, $limit);
        foreach ($r as $k=>$v){
            $r[$k]['payment']=json_decode($v['payment'],true);
        }
        $total = OrderModel::getScalar("uid=$uid", 'count(id)');
        return [
            'list' => $r,
            'total' => $total,
        ];
    }

    public static function createOrder($contacts = [], $name, $email, $phone, $useFund = 0, $useProtect, $rental = [], $message, $tripId, $cabinId, $oneSelf, $course = []) {
        foreach ($contacts as $item) {
            if (empty($item['name']) || empty($item['gender'])) {
                return [
                    'err' => 1,
                    'msg' => '参数错误'
                ];
            }
        }
        Contact::checkContacts($contacts);

        /** @var \api\models\User $user */
        $user = Yii::$app->user->getIdentity();
        $occupancy = Occupancy::chooseOccupancy($tripId, $cabinId, $oneSelf);
        if (!$occupancy) {
            return [
                'err' => 2,
                'msg' => '无合适仓位',
            ];
        }
        $orderId = self::generateOrderid();
        $time = (int)(microtime(true) * 1000);
        $data = [
            'order_id' => $orderId,
            'order_status' => OrderStatus::UNPAID,
            'payment_status' => PaymentStatus::UNPAID,
            'contact' => json_encode($contacts, JSON_UNESCAPED_UNICODE),
            'uid' => $user->id,
            'username' => $name,
            'email' => $email,
            'phone' => $phone,
            'message' => $message ?: '',
            'trip_id' => $tripId,
            'cabin_id' => $cabinId,
            'one_self' => $oneSelf ? 1 : 0,
            'use_protect' => $useProtect ?: '',
            'ctime' => $time,
            'utime' => $time,
            'occupancy_id' => $occupancy['id'],
            'price' => ceil(Currency::eur2cnyYuan($occupancy['price'])) * 100 * count($contacts), //单位人民币分
            'unitprice' => $occupancy['price'] * 100, //单位分
            'exchange_rate' => Currency::getEur2CnyRate(),
            'ext' => '{}',
        ];
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if ($useFund) {
                $origFundAmount = $user->getAttribute('fund_amount');
                if ($origFundAmount > 0) {
                    $fundRatio = Yii::$app->params['fundRatio'];
                    $discountAmount = min($data['price'] * $fundRatio, $origFundAmount);
                    $data['price'] -= $discountAmount;
                    $data['fund_amount'] = $discountAmount;
                    User::useFundAmount($user->id, $discountAmount);
                    $newFund = User::getFundAmount($user->id);
                    if ($newFund < 0) {
                        $transaction->rollBack();
                        return [
                            'err' => 1,
                            'msg' => '基金不足'
                        ];
                    }
                }
            }
            OrderModel::insert($data);
            OrderStatusFlow::insert([
                'order_id' => $orderId,
                'type' => OrderStatusFlow::TYPE_ORDER,
                'status' => OrderStatus::UNPAID,
                'ctime' => $time,
                'reason'=>'用户下单',
            ]);
            OrderStatusFlow::insert([
                'order_id' => $orderId,
                'type' => OrderStatusFlow::TYPE_PAYMENT,
                'status' => PaymentStatus::UNPAID,
                'ctime' => $time,
                'reason'=>'用户下单',
            ]);
            Contact::saveContacts($user->id, $contacts);
            $transaction->commit();
            return [
                'err' => 0,
                'orderId' => $orderId,
                'price' => 1000,
            ];
        } catch (\Exception $e) {
            $transaction->rollBack();
            return [
                'err' => 1,
                'msg' => $e->getMessage()
            ];
        }
    }

    public static function userRequestPay($orderId) {
        $params = [
            "mer_id" => "60000100",
            "ret_url" => "http://www.xxx.com/xxxx.php",
            "notify_url" => "http://www.xxx.com/xxxx.php",
            "goods_inf" => "商品描述",
            "order_id" => $orderId,
            "mer_date" => date("Ymd"),
            "amount" => "1",
            "interface_type" => "01",
        ];
        $service = new \UmfService("60000100", "C:/60000100_.key.pem");
        $web_pay_get_url = $service->WebFrontPagePayMap($params);
        var_dump($web_pay_get_url);
    }

    /**
     * 异步成功支付时，调用此方法
     * @param $orderId
     * @return array
     */
    public static function pay($orderId, $payTime = null, $payType = '') {
        $r = self::getFormattedOrder($orderId);
        if (!$r) return [
            'err' => 1,
            'msg' => '订单不存在'
        ];
        if ($r['order_status'] == OrderStatus::UNPAID && $r['supply_status'] == SupplyStatus::UNSET && $r['payment_status'] == PaymentStatus::UNPAID && $r['account_status'] == AccountStatus::UNSET) {
            if ($payTime) {
                $time = strtotime($payTime) * 1000;
            } else {
                $time = (int)(microtime(true) * 1000);
            }
            if (true) {
                $data = [
                    'order_status' => OrderStatus::PAID,
                    'payment_status' => PaymentStatus::PAID,
                ];
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $num = OrderModel::update($data, "order_id='$orderId'");
                    if (!$num) {
                        $transaction->rollBack();
                        return [
                            'err' => 2,
                            'msg' => '重复操作'
                        ];
                    }
                    OrderModel::update([
                        'utime' => $time,
                        'payment' => json_encode([
                            'type' => $payType,
                        ])
                    ], "order_id='$orderId'");
                    OrderStatusFlow::insert([
                        'order_id' => $orderId,
                        'type' => OrderStatusFlow::TYPE_ORDER,
                        'status' => OrderStatus::PAID,
                        'ctime' => $time,
                        'reason'=>'用户支付',
                    ]);
                    OrderStatusFlow::insert([
                        'order_id' => $orderId,
                        'type' => OrderStatusFlow::TYPE_PAYMENT,
                        'status' => PaymentStatus::PAID,
                        'ctime' => $time,
                        'reason'=>'用户支付',
                    ]);
                    $transaction->commit();
                    return [
                        'err' => 0,
                    ];
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    return [
                        'err' => 1,
                        'msg' => $e->getMessage()
                    ];
                }
            } else {
                return [
                    'err' => 4,
                    'msg' => '支付错误'
                ];
            }
        } else {
            return [//caution!
                    'err' => 2,
                    'msg' => '状态非法'
            ];
        }
    }

    public static function userPay($orderId) {
        $r = self::getFormattedOrder($orderId);
        if (!$r) return [
            'err' => 1,
            'msg' => '订单不存在'
        ];
        if (Yii::$app->user->isGuest || $r['uid'] != Yii::$app->user->id) {
            return [
                'err' => 3,
                'msg' => '无权限',
            ];
        }
        if ($r['order_status'] == OrderStatus::UNPAID && $r['supply_status'] == SupplyStatus::UNSET && $r['payment_status'] == PaymentStatus::UNPAID && $r['account_status'] == AccountStatus::UNSET) {
            //todo actual pay logic
            $time = (int)(microtime(true) * 1000);
            if (true) {
                $data = [
                    'order_status' => OrderStatus::PAID,
                    'payment_status' => PaymentStatus::PAID,
                ];
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $num = OrderModel::update($data, "order_id=$orderId");
                    if (!$num) {
                        $transaction->rollBack();
                        return [
                            'err' => 2,
                            'msg' => '重复操作'
                        ];
                    }
                    OrderModel::update(['utime' => $time], "order_id=$orderId");
                    OrderStatusFlow::insert([
                        'order_id' => $orderId,
                        'type' => OrderStatusFlow::TYPE_ORDER,
                        'status' => OrderStatus::PAID,
                        'ctime' => $time,
                    ]);
                    OrderStatusFlow::insert([
                        'order_id' => $orderId,
                        'type' => OrderStatusFlow::TYPE_PAYMENT,
                        'status' => PaymentStatus::PAID,
                        'ctime' => $time,
                    ]);
                    $transaction->commit();
                    return [
                        'err' => 0,
                    ];
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    return [
                        'err' => 1,
                        'msg' => $e->getMessage()
                    ];
                }
            } else {
                return [
                    'err' => 4,
                    'msg' => '支付错误'
                ];
            }
        } else {
            return [
                'err' => 2,
                'msg' => '状态非法'
            ];
        }
    }

    public static function externalPay($orderId) {

    }

    public static function userCancel($uid, $orderId) {
        $order = OrderModel::getOne("order_id='$orderId'");
        if ($order['uid'] != $uid) {
            return [
                'err' => 1,
                'msg' => '无权限',
            ];
        }
        //TODO check order status
        if ($order['order_status'] == OrderStatus::UNPAID && $order['supply_status'] == SupplyStatus::UNSET && $order['payment_status'] == PaymentStatus::UNPAID && $order['account_status'] == AccountStatus::UNSET) {
            $time = (int)(microtime(true) * 1000);
            $data = [
                'order_id' => $orderId,
                'order_status' => OrderStatus::CLOSED,
                'payment_status' => PaymentStatus::CANCEL,
                'utime' => $time,
            ];

            $transaction = Yii::$app->db->beginTransaction();
            try {
                $order['fund_amount'] && User::addFundAmount($order['uid'], $order['fund_amount']);
                OrderModel::update($data, "order_id='$orderId'");
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_ORDER,
                    'status' => OrderStatus::CLOSED,
                    'ctime' => $time,
                    'reason' => '用户取消',
                ]);
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_PAYMENT,
                    'status' => PaymentStatus::CANCEL,
                    'ctime' => $time,
                    'reason' => '用户取消',
                ]);
                $transaction->commit();
                return [
                    'err' => 0,
                ];
            } catch (\Exception $e) {
                $transaction->rollBack();
                return [
                    'err' => 1,
                    'msg' => $e->getMessage()
                ];
            }
        } else {
            return [
                'err' => 1,
                'msg' => '状态异常'
            ];
        }
    }

    public static function overtimeCancel() { }

    public static function getFormattedOrder($orderId) {
        $order = OrderModel::getOne("order_id='$orderId'");
        if (!$order) return false;
        $order['contact'] = json_decode($order['contact'], true);
        $order['ext'] = $order['ext'] ? json_decode($order['ext'], true) : [];
        return $order;
    }

    public static function clientEnName($cnName) {
        $pinyin = new Pinyin();
        $pys = $pinyin->name($cnName);
        $lastName = ucfirst(array_shift($pys));
        return [
            ucfirst(implode('', $pys)),
            $lastName
        ];
    }

    /**
     * 后台方法
     */
    public static function platformConfirm($orderId) {
        $order = self::getFormattedOrder($orderId);
        if (!$order) return [
            'err' => 1,
            'msg' => '订单不存在'
        ];
        if ($order['order_status'] == OrderStatus::PAID && $order['supply_status'] == SupplyStatus::UNSET && $order['payment_status'] == PaymentStatus::PAID && $order['account_status'] == AccountStatus::UNSET) {
            $time = (int)(microtime(true) * 1000);
            $data = [
                'supply_status' => SupplyStatus::ORDER,
            ];
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $num = OrderModel::update($data, "order_id='$orderId'");
                if (!$num) {
                    $transaction->rollBack();
                    return [
                        'err' => 2,
                        'msg' => '重复操作'
                    ];
                }
                if (!isset($order['ext']['clientEnName'])) $order['ext']['clientEnName'] = self::clientEnName($order['contact'][0]['name']);
                $r = DiveBooker::makeOrder($order['trip_id'], $order['occupancy_id'], count($order['contact']), $order['ext']['clientEnName']);
                if ($r['err'] != 0) {
                    $transaction->rollBack();
                    return [
                        'err' => 2,
                        'msg' => 'Booker下单失败:' . $r['msg'],
                    ];
                }
                OrderModel::update([
                    'utime' => $time,
                    'booker_orderid' => $r['bookerOrderId']
                ], "order_id='$orderId'");
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_SUPPLY,
                    'status' => SupplyStatus::ORDER,
                    'ctime' => $time,
                    'reason' => '平台确认，下单给供应商',
                ]);
                $transaction->commit();
                return [
                    'err' => 0,
                ];
            } catch (\Exception $e) {
                $transaction->rollBack();
                return [
                    'err' => 1,
                    'msg' => $e->getMessage()
                ];
            }
        } else {
            return [
                'err' => 3,
                'msg' => '状态异常: 用户尚未支付?'
            ];
        }
    }

    public static function supplierConfirm($orderId) {
        $order = self::getFormattedOrder($orderId);
        if (!$order) return [
            'err' => 1,
            'msg' => '订单不存在'
        ];
        if ($order['order_status'] == OrderStatus::PAID && $order['supply_status'] == SupplyStatus::ORDER && $order['payment_status'] == PaymentStatus::PAID && $order['account_status'] == AccountStatus::UNSET) {
            $time = (int)(microtime(true) * 1000);
            $data = [
                'order_status' => OrderStatus::CONFIRMED,
                'supply_status' => SupplyStatus::CONFIRMED,
                'account_status' => AccountStatus::TO_REMIT,
            ];
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $num = OrderModel::update($data, "order_id='$orderId'");
                if (!$num) {
                    $transaction->rollBack();
                    return [
                        'err' => 2,
                        'msg' => '重复操作'
                    ];
                }
                OrderModel::update(['utime' => $time,], "order_id='$orderId'");
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_ORDER,
                    'status' => OrderStatus::CONFIRMED,
                    'ctime' => $time,
                    'reason' => '平台确认',
                ]);
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_SUPPLY,
                    'status' => SupplyStatus::CONFIRMED,
                    'ctime' => $time,
                    'reason' => '收到供应商邮件',
                ]);
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_ACCOUNT,
                    'status' => AccountStatus::TO_REMIT,
                    'ctime' => $time,
                    'reason' => '收到供应商邮件',
                ]);
                $transaction->commit();
                return [
                    'err' => 0,
                ];
            } catch (\Exception $e) {
                $transaction->rollBack();
                return [
                    'err' => 1,
                    'msg' => $e->getMessage()
                ];
            }
        } else {
            return [
                'err' => 3,
                'msg' => '状态异常'
            ];
        }
    }

    public static function remitToSupplier($orderId) {
        $order = self::getFormattedOrder($orderId);
        if (!$order) return [
            'err' => 1,
            'msg' => '订单不存在'
        ];
        if ($order['order_status'] == OrderStatus::CONFIRMED && $order['supply_status'] == SupplyStatus::CONFIRMED && $order['payment_status'] == PaymentStatus::PAID && $order['account_status'] == AccountStatus::TO_REMIT) {
            $time = (int)(microtime(true) * 1000);
            $data = [
                'account_status' => AccountStatus::REMITTING,
            ];
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $num = OrderModel::update($data, "order_id='$orderId'");
                if (!$num) {
                    $transaction->rollBack();
                    return [
                        'err' => 2,
                        'msg' => '重复操作'
                    ];
                }
                OrderModel::update(['utime' => $time,], "order_id='$orderId'");
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_ACCOUNT,
                    'status' => AccountStatus::REMITTING,
                    'ctime' => $time,
                    'reason' => '后台操作',
                ]);
                $transaction->commit();
                return [
                    'err' => 0,
                ];
            } catch (\Exception $e) {
                $transaction->rollBack();
                return [
                    'err' => 1,
                    'msg' => $e->getMessage()
                ];
            }
        } else {
            return [
                'err' => 3,
                'msg' => '状态异常'
            ];
        }
    }

    public static function supplierRemittanceReceived($orderId) {
        $order = self::getFormattedOrder($orderId);
        if (!$order) return [
            'err' => 1,
            'msg' => '订单不存在'
        ];
        if ($order['order_status'] == OrderStatus::CONFIRMED && $order['supply_status'] == SupplyStatus::CONFIRMED && $order['payment_status'] == PaymentStatus::PAID && $order['account_status'] == AccountStatus::REMITTING) {
            $time = (int)(microtime(true) * 1000);
            $data = [
                'account_status' => AccountStatus::REMITTED,
                'supply_status'=>SupplyStatus::REMITTANCE_RECEIVED,
            ];
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $num = OrderModel::update($data, "order_id='$orderId'");
                if (!$num) {
                    $transaction->rollBack();
                    return [
                        'err' => 2,
                        'msg' => '重复操作'
                    ];
                }
                OrderModel::update(['utime' => $time,], "order_id='$orderId'");
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_ACCOUNT,
                    'status' => AccountStatus::REMITTED,
                    'ctime' => $time,
                    'reason' => '供应商确认收汇',
                ]);
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_SUPPLY,
                    'status' => SupplyStatus::REMITTANCE_RECEIVED,
                    'ctime' => $time,
                    'reason' => '供应商确认收汇',
                ]);
                $transaction->commit();
                return [
                    'err' => 0,
                ];
            } catch (\Exception $e) {
                $transaction->rollBack();
                return [
                    'err' => 1,
                    'msg' => $e->getMessage()
                ];
            }
        } else {
            return [
                'err' => 3,
                'msg' => '状态异常'
            ];
        }
    }

    public static function orderStart($orderId) {

    }

    public static function orderComplete($orderId) { }

    /**
     * 检查支付超时
     * @param $order
     */
    public static function orderPayTimeout(&$order) {
        if ($order['order_status'] == OrderStatus::UNPAID) {
            $now = (int)(microtime(true) * 1000);
            if ($now >= $order['ctime'] + Yii::$app->params['orderPayTimeout'] * 1000) {
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $data = [
                        'order_status' => OrderStatus::CLOSED,
                        'payment_status' => PaymentStatus::CANCEL,
                    ];
                    $num = OrderModel::update($data, "order_id='{$order['order_id']}'");
                    if (!$num) {
                        $transaction->rollBack();
                        return;
                    }
                    $order['order_status']=OrderStatus::CLOSED;
                    $order['utime']=$now;
                    OrderModel::update(['utime' => $now,], "order_id='{$order['order_id']}'");
                    OrderStatusFlow::insert([
                        'order_id' => $order['order_id'],
                        'type' => OrderStatusFlow::TYPE_ORDER,
                        'status' => OrderStatus::CLOSED,
                        'ctime' => $now,
                        'reason' => '支付超时取消',
                    ]);
                    OrderStatusFlow::insert([
                        'order_id' => $order['order_id'],
                        'type' => OrderStatusFlow::TYPE_PAYMENT,
                        'status' => PaymentStatus::CANCEL,
                        'ctime' => $now,
                        'reason' => '支付超时取消',
                    ]);
                    $transaction->commit();
                } catch (\Exception $e) {
                    $transaction->rollBack();
                }
            }
        }
    }

    public static function checkStart() { }

    public static function orderEnd() { }

    public static function checkEnd() { }

    public static function userRequestRefund() {

    }


    public static function userRefundFail() { }

    public static function supplierConfirmFail() {

    }

    /**
     * 更新状态为退款成功，收到第三方支付异步回调时 触发
     * 目前微信支付用这种方式、支付宝无异步通知，退款请求时直接返回结果
     * @param $order
     * @return array
     */
    public static function refundComplete(&$order) {
        if($order['order_status']==OrderStatus::REFUNDING && $order['payment_status']==PaymentStatus::REFUNDING){
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $orderId=$order['order_id'];
                $data = [
                    'order_status' => OrderStatus::CLOSED,
                    'payment_status'=>PaymentStatus::REFUNDED,
                ];
                if (!OrderModel::update($data, "order_id='$orderId'")) {
                    $transaction->rollBack();
                    return [
                        'err' => 2,
                        'msg' => '重复操作'
                    ];
                }
                $res = [];
                $time = (int)(microtime(true) * 1000);
                OrderModel::update([
                    'utime' => $time,
                ], "order_id='$orderId'");
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_ORDER,
                    'status' => OrderStatus::CLOSED,
                    'ctime' => $time,
                    'reason' => '异步通知退款成功',
                ]);
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_PAYMENT,
                    'status' => PaymentStatus::REFUNDED,
                    'ctime' => $time,
                    'reason' => '异步通知退款成功',
                ]);
                $transaction->commit();
                return [
                    'err' => 0,
                    'res' => $res,
                ];
            } catch (\Exception $e) {
                $transaction->rollBack();
                return [
                    'err' => 1,
                    'msg' => $e->getMessage()
                ];
            }
        } else {
            return [
                'err' => 3,
                'msg' => '状态异常'
            ];
        }
    }

    /**
     * 管理员操作退款,发起支付退款
     * 退款结果：支付宝接口直接返回，微信支付需处理异步通知
     * 先开启事务 取消订单，再执行退款，异常则回滚
     */
    public static function platformRefundManually(&$order) {
        if ($order['order_status'] == OrderStatus::PAID
            && $order['supply_status'] == SupplyStatus::UNSET
            && $order['payment_status'] == PaymentStatus::PAID
            && $order['account_status'] == AccountStatus::UNSET
            || $order['order_status'] == OrderStatus::PAID
            && $order['supply_status'] == SupplyStatus::ORDER
            && $order['payment_status'] == PaymentStatus::PAID
            && $order['account_status'] == AccountStatus::UNSET
            || $order['order_status'] == OrderStatus::CONFIRMED
            && $order['supply_status'] == SupplyStatus::CONFIRMED
            && $order['payment_status'] == PaymentStatus::PAID
            && $order['account_status'] == AccountStatus::TO_REMIT) {

            if (!isset($order['payment']['type'])) {
                return [
                    'err' => 2,
                    'msg' => '状态异常'
                ];
            }

            $time = (int)(microtime(true) * 1000);

            if ($order['payment']['type'] == self::PAY_TYPE_ALI) {
                $data = [
                    'order_status' => OrderStatus::CLOSED,
                    'payment_status' => PaymentStatus::REFUNDED,
                ];
            }else{
                $data = [
                    'order_status' => OrderStatus::REFUNDING,
                    'payment_status' => PaymentStatus::REFUNDING,
                ];
            }

            if ($order['supply_status'] != SupplyStatus::UNSET) {
                $data['supply_status'] = SupplyStatus::CANCEL;
            }
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $orderId=$order['order_id'];
                $num = OrderModel::update($data, "order_id='$orderId'");
                if (!$num) {
                    $transaction->rollBack();
                    return [
                        'err' => 2,
                        'msg' => '重复操作'
                    ];
                }
                $res = [];
                $ext = [];
                if ($order['payment']['type'] == self::PAY_TYPE_ALI) {
                    $tmp = Alipay::refund($order);
                    if ($tmp['err'] == 0) {
                        $res = $tmp['data'];
                        $ext['alipay']['refund_trade_no'] = $res['trade_no'];
                    } else {
                        $transaction->rollBack();
                        return $tmp;
                    }
                } elseif ($order['payment']['type'] == self::PAY_TYPE_WECHAT) {
                    $tmp = WechatPay::refund($order);
                    if ($tmp['err'] == 0) {
                        $res = $tmp['data'];
                        $ext['wechatpay']['refund_trade_no'] = $res['refund_id'];
                    } else {
                        $transaction->rollBack();
                        return $tmp;
                    }
                }
                OrderModel::update([
                    'utime' => $time,
                    'ext' => json_encode(array_merge($order['ext'], $ext)),
                ], "order_id='$orderId'");
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_ORDER,
                    'status' => $order['payment']['type'] == self::PAY_TYPE_ALI ? OrderStatus::CLOSED : OrderStatus::REFUNDING,
                    'ctime' => $time,
                    'reason' => '用户申请退款',
                ]);
                $order['supply_status'] != SupplyStatus::UNSET && OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_SUPPLY,
                    'status' => SupplyStatus::CANCEL,
                    'ctime' => $time,
                    'reason' => '用户申请退款',
                ]);
                OrderStatusFlow::insert([
                    'order_id' => $orderId,
                    'type' => OrderStatusFlow::TYPE_PAYMENT,
                    'status' => $order['payment']['type'] == self::PAY_TYPE_ALI ? PaymentStatus::REFUNDED : PaymentStatus::REFUNDING,
                    'ctime' => $time,
                    'reason' => '用户申请退款',
                ]);
                $transaction->commit();
                return [
                    'err' => 0,
                    'res' => $res,
                ];
            } catch (\Exception $e) {
                $transaction->rollBack();
                return [
                    'err' => 1,
                    'msg' => $e->getMessage()
                ];
            }
        } else {
            return [
                'err' => 3,
                'msg' => '状态异常'
            ];
        }

    }

    public static function platformRefundComplete() { }

    public static function platformRefundFail() { }

    public static function deleteOrder($orderId) {
        $uid = Yii::$app->user->getId();
        $item = OrderModel::getOne(['order_id' => $orderId]);
        if ($uid != $item['uid']) {
            return [
                'err' => 2,
                'msg' => '无此权限'
            ];
        }
        $r = OrderModel::update(['deleted' => 1], "order_id=$orderId");
        if ($r) {
            return ['err' => 0];
        } else {
            return [
                'err' => 3,
                '未知错误'
            ];
        }
    }
}
